import * as echarts from '../../ec-canvas/echarts.js';

const app = getApp();
const DB = wx.cloud.database().collection("Search_history")
var list_value = []
var list_key = []
var Ddata = []
var Dsubject = []
var Dacademician = []
var Dorganization = []
var Dorganization_info = []
var area_1 = []
var area_2 = []
var Ds_area1 = []
var Do_list = []
var bar_hindex = []
var bar_cited = []
var bar_num = []
var bar_affiliate = []
var bar_author = []
var option = {}
var option_area = {}
var option_bar = {}
var option_tree = {}
var intro = ""
var sizelist = []
var multiply = 0.1
var sum_multiply = 0.05
var blendent = ["#845EC2","#D65DB1","#FF6F91","#FF6F91","#FF9671","#FFC75F","#F9F871","#2C73D2","#0081CF","#0089BA","#008E9B","#008F7A","#B39CD0","#FBEAFF","#00C9A7","#C4FCEF","#4D8076","#4B4453","#B0A8B9","#C34A36","#FF8066"]
var c0 = parseInt(Math.random()*10+10)

function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);
  chart.setOption(app.globalData.parameter);
  return chart;
}

function initchart_area(canvas, width, height, dpr) {
  const achart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(achart);
  achart.setOption(option_area);
  return achart;
}

function initchart_bar(canvas, width, height, dpr) {
  const bchart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(bchart);
  bchart.setOption(option_bar);
  return bchart;
}

function initchart_tree(canvas, width, height, dpr) {
  const tchart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(tchart);
  tchart.setOption(option_tree);
  return tchart;
}

function sortByInt (array, key) {
  return array.sort(function (b, a) {
    var x = a[key]
    var y = b[key]
    return y - x
  })
}

Page({
  data: {
    baidu_output:{},
    stime:"",
    ecline: {
      onInit:initChart
    },
    ecpie2: {
      onInit:initchart_area
    },
    ecpie3: {
      onInit:initchart_bar
    },
    ecpie4: {
      onInit:initchart_tree
    },
    weight_1:"",
    object_sum:"",
    organzation_top5:"",
    o1_proportion:"",
    userID:null
  },

  onLoad(options) {
    list_value.splice(0, list_value.length)
    list_key.splice(0, list_key.length)
    Ddata.splice(0, Ddata.length)
    Dsubject.splice(0, Dsubject.length)
    Dacademician.splice(0, Dacademician.length)
    Dorganization.splice(0,Dorganization.length)
    area_1.splice(0, area_1.length)
    area_2.splice(0, area_2.length)
    Ds_area1.splice(0, Ds_area1.length)
    Do_list.splice(0, Do_list.length)
    bar_hindex.splice(0, bar_hindex.length)
    bar_cited.splice(0, bar_cited.length)
    bar_num.splice(0, bar_num.length)
    bar_affiliate.splice(0, bar_affiliate.length)
    bar_author.splice(0, bar_author.length)
    sizelist.splice(0,sizelist.length)
    option = {}
    option_area = {}
    option_bar = {}
    intro = ""
    multiply = 0.1
    sum_multiply = 0.05

    console.log("结果传值",JSON.parse(decodeURIComponent(options.baidu)))
    this.getOpenid()
    this.setData({
      baidu_output: JSON.parse(decodeURIComponent(options.baidu)),
      stime:new Date(Date.parse(new Date())+ 60*60*1000*8).toISOString().substring(0, 10) +" "+ new Date(Date.parse(new Date())+ 60*60*1000*8).toISOString().substring(11, 19)
    })
    console.log(this.data.baidu_output)
    intro = this.data.baidu_output.data.current_kw_data.trend.intro
    Ddata = this.data.baidu_output.data.current_kw_data.trend.chartData
    Ddata.forEach(element => {
      list_value = list_value.concat(element.value)
      list_key = list_key.concat(element.time)
    });
    console.log("对应值",list_value)
    console.log("年份",list_key)
    Dsubject = this.data.baidu_output.data.current_kw_data.subject.chartData
    var totalarticle = this.data.baidu_output.data.current_kw_data.trend.totalArticle
    sizelist = sizelist.concat(Math.round(parseInt(totalarticle)*0.01))
    console.log("ride",totalarticle)
    //关系节点图大小比例设置
    if (Math.round(parseInt(totalarticle)*0.1) > 1000) {
      sum_multiply = 0.002
      multiply = 0.003
    } else if (500 > Math.round(parseInt(totalarticle)*0.1)> 200) {
      sum_multiply = 0.001
      multiply = 0.0015
    } else {
      sum_multiply = 0.1
      multiply = 0.15
    }
    console.log("sum_multiply",Math.round(parseInt(totalarticle)*sum_multiply))
    Dsubject.forEach(element_c1=> {
      var c1 = parseInt(Math.random()*10+10)
      var branch = {"name":" ","children":null,"value":0,"symbolSize":0,"itemStyle":{"color" : blendent[c1]}}
      branch.name = element_c1.name
      branch.value = element_c1.weight
      branch.symbolSize = Math.round(parseInt(element_c1.weight)*multiply)
      Ds_area1 = []
      element_c1.children.forEach(element_c2=> {
        var branch_cd = {"name":element_c2.name,"value":parseInt(element_c2.weight),"symbolSize":Math.round(parseInt(element_c2.weight)*multiply)}
        Ds_area1 = Ds_area1.concat(branch_cd)
      })
      branch.children = Ds_area1
      console.log("branch",branch)
      area_1 = area_1.concat(branch)
    })
    console.log("bulid_dac_children",area_1)
    area_1.forEach(buildbranch=> {
      var c2 = parseInt(Math.random()*10+10)
      var area_children = {"name":buildbranch.name,"children":buildbranch.children,"value":buildbranch.value,"symbolSize":buildbranch.symbolSize,"itemStyle":{"color" : blendent[c2]}}
      area_2 = area_2.concat(area_children)
    })
    console.log("build_da_children",area_2)
    Dacademician = this.data.baidu_output.data.current_kw_data.academician.chartData
    for (let i = 0; i < 10; i++) {
      bar_author = bar_author.concat(Dacademician[i].name)
      bar_affiliate = bar_affiliate.concat(Dacademician[i].affiliate)
      bar_cited = bar_cited.concat(parseInt(Dacademician[i].cited_count))
      bar_hindex = bar_hindex.concat(parseInt(Dacademician[i].h_index))
      bar_num = bar_num.concat(parseInt(Dacademician[i].paper_count))
    }
    Dorganization = this.data.baidu_output.data.current_kw_data.organization.chartData
    Dorganization_info = this.data.baidu_output.data.current_kw_data.organization
    var suborganzation = ""
    for (var i=0; i<5; i++) {
      suborganzation = suborganzation + Dorganization[i].name + "，"
    }
    this.setData({
      o1_proportion:parseInt(Dorganization[0].value / Dorganization_info.totalArticle * 100)+"%",
      organzation_top5:suborganzation
    })
    console.log("Dorganization",Dorganization)
    Dorganization.forEach(element_c4=> {
      var rate = element_c4.value / Dorganization_info.totalArticle *100
      var tree = {"name":element_c4.name+"："+rate.toFixed(3)+'%',"value":parseInt(element_c4.value)}
      Do_list = Do_list.concat(tree)
    })
    console.log("Do_list",Do_list)
    // 折线图
    option = {
      grid: {
        //左边距x,右边距x2,上边距y,下边距y2
        containLabel: true,
        x: 0,
        y: 10,
        y2: 0
      },
      tooltip: {
        show: true,
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: list_key,
        // show: false
      },
      yAxis: {
        x: 'center',
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        }
        // show: false
      },
      series: [{
        name: intro,
        type: 'line',
        smooth: true,
        data: list_value
      }]
    }
    app.globalData.parameter = option
    // 矩形树图
    var data_area ={
      "name": this.data.baidu_output.data.current_kw,
      // Math.round(parseInt(this.data.baidu_output.data.current_kw_data.trend.totalArticle)*sum_multiply)
      "symbolSize": 100,
      "itemStyle":{"color" : blendent[c0]},
      "children": area_2
    }
    option_area = {
      tooltip: {
        trigger: 'item',
        triggerOn: 'mousemove'
      },
      grid: {
        containLabel: true,
        x: 0,
        y: 0
      },
      series: [{
        roam: true,//移动+放大
 			  roam: 'scale',// 放大
 			  roam: 'move',// 移动
        type: 'tree',
        layout:'radial', //分布
        initialTreeDepth: 1, //默认展开层级，-1时默认展开所有
        animationDurationUpdate: 750,
        name: 'tree1',
        data: [data_area],
        symbol: 'circle', //circle,rect,roundRect,triangle,diamond,pin,arrow,emptyCircle,none
        // symbolSize: function (value, params) {//改变节点大小
        //   var nodesize = sizelist;
        //   return nodesize[params.dataIndex]
        // },
        emphasis: {
          focus: 'descendant'
        },
        label: {
          fontsize: 6
        },
        leaves: {
          label: {
            position: 'right',
            verticalAlign: 'middle',
            align: 'left'
          }
        },
      }]
    }
    var data_ori = this.data.baidu_output.data.current_kw_data
    var branch_weight = data_ori.subject.chartData[0].weight
    var subobject = ""
    for (var i=0; i<data_ori.subject.chartData.length; i++) {
      subobject = subobject + data_ori.subject.chartData[i].name + "，"
    }
    this.setData({
      weight_1:parseInt(branch_weight),
      object_sum:subobject
    })
    app.globalData.parameter_2 = option_area
    // 柱状图_作者
    option_bar = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        containLabel: true,
        x: 0,
        x2: 0,
        y: 10,
        y2: 0
      },
      xAxis: {
        type: 'category',
        data: bar_author,
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: "paper_count",
          data: bar_num,
          type: 'bar',
          showBackground: true,
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.2)'
          }
        }, {
          name: "cited_count",
          data: bar_cited,
          type: 'bar',
          showBackground: true,
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.2)'
          }
        }, {
          name: "h_index",
          data: bar_hindex,
          type: 'bar',
          showBackground: true,
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.2)'
          }
        }
      ]
    }
    // 矩形树图_机构
    option_tree = {
      title: {
        text: Dorganization_info.intro,
        left: 'left',
        top: 0,
        textStyle: {
          color: 'gray',
          fontFamily: '黑体',
          fontSize: 14
        }
      },
      tooltip: {
        show: false,
        trigger: 'item',
        // formatter: function (a) {
        //   var str = '类别:';
        //   return str.concat(
        //     a.name + '\n\n' + '次数:',
        //     a.value + '\n\n' + '占比:',
        //     ((a.value / 2010) * 100).toFixed(2) + '%'
        //   );
        // }
      },
      grid: {
        containLabel: true,
        x: 0,
        x2: 0,
        y: 0,
        y2: 0
      },
      series: [
        {
          type: 'treemap',
          center: ['50%', '50%'],
          // label: {
          //   show: true,
          //   formatter: function (a) {
          //     var str = '类别:';
          //     return str.concat(
          //       a.name + '\n\n' + '次数:',
          //       a.value + '\n\n' + '占比:',
          //       ((a.value / 2010) * 100).toFixed(2) + '%'
          //     );
          //   },
          //   //这里的重点在于设置百分比
          //   position: 'inside',
          //   color: 'black',
          //   fontSize: 14
          // },
          color: [
            '#6EBBFB',
            '#00D2FF',
            '#00E5E9',
            '#4DF2C0',
            '#A8F992',
            '#F9F871',
            '#996DBD',
            '#8B88D9',
            '#D5F4FF',
            '#CCE8E4'
          ],
          data: [
            {
              name: '相关机构总发文量：' + Dorganization_info.totalArticle,
              value: Dorganization.totalArticle,
              children: Do_list
            }
          ]
        }
      ]
    }
  },

  elink() {
    wx.navigateTo({
      url: '../baike/baike?link=' + this.data.baidu_output.data.baikeurl,
    })
  },

  getOpenid() {
    wx.cloud.callFunction({
      config:{ env: 'cloud1-2g6vpgs796710242' },
      name:"Get_useropenid"
    }).then(res=>{
      console.log("获取openid成功",res.result.event.userInfo.openId)
      this.setData({
        userID:res.result.event.userInfo.openId
      })
    }).catch(err=>{
      console.log("获取失败",err)
    })
  },

  addreview() {
    console.log(this.data.userID)
    console.log(this.data.baidu_output.data.current_kw)
    // 作者筛选
    var timestamp = new Date().toJSON().substring(0, 10)
    var feedback = this.data.baidu_output.data
    var hotyp = ""
    var hotauthor = sortByInt(feedback.current_kw_data.academician.chartData,"paper_count")[19]
    var time = feedback.current_kw_data.trend.intro
    feedback.current_kw_data.trend.chartData.forEach(element=>{
      if (element.time==feedback.current_kw_data.trend.hotYear) {
        hotyp = element.value
      }
    })
    console.log("hotauthor",hotauthor)
    //趋势粗略计算
    var peak = parseInt(feedback.current_kw_data.trend.hotYear)
    var origin  = feedback.current_kw_data.trend.chartData[0].value
    var arrlength = feedback.current_kw_data.trend.chartData.length-1
    var end = feedback.current_kw_data.trend.chartData[arrlength].value
    var trend_explain = ""
    console.log("peak",peak)
    console.log("origin",origin)
    console.log("end",end)
    if (origin > end) {
      if ((peak-origin)>(end-peak)) {
        trend_explain="早期整体上升但近年数值下降的"
      } else {
        trend_explain="早期局部上升但整体数值下降的"
      }
    } else if (origin < end) {
      if ((peak-origin)>(end-peak)) {
        trend_explain="早期上升显著后期增速放缓，但整体数字提升的"
      } else {
        trend_explain="整体数值增长末期有局部回落的"
      }
    } else if (origin == end) {
      trend_explain="数值上过去大幅增长但近年显著回落的"
    }
    var state = "基于百度学术数据库数据，设定检索词为"+feedback.current_kw+"，检索时间区间为"+time+"，共得到文献"+feedback.current_kw_data.trend.totalArticle+"篇。其中论文发表量在"+feedback.current_kw_data.trend.hotYear+"年达到峰值，累计产出"+hotyp+"篇。年载文量呈现"+trend_explain+"的趋势。"+"在深度研究作者方面，"+"来自"+hotauthor.affiliate+"的"+hotauthor.name+"在该领域的发文量累计最多，共计"+hotauthor.paper_count+"篇。其被引量和H因子指数分别为"+hotauthor.cited_count+"和"+hotauthor.h_index+"。"
    console.log("趋势说明",trend_explain)
    // wx.cloud.callFunction({
    //   config:{ env: 'cloud1-2g6vpgs796710242' },
    //   name:"Check_review",
    //   data: {
    //     pass_openid:this.data.userID,
    //     pass_subject:this.data.baidu_output.data.current_kw,
    //   }
    // })
    DB.where({
      _openid:this.data.userID,
      subject:this.data.baidu_output.data.current_kw,
    })
    .get()
    .then(res=>{
      console.log("查重",res)
      if(res.data.length>0) {
        var equltime = res.data[0].time===new Date().toJSON().substring(0, 10)
        if(equltime==true) {
          wx.showToast({
            title: '不要重复保存哦',
            icon:"none",
            duration:3000
          })
        } else if (equltime==false) {
          console.log("更新")
          DB.where({
            openid:this.data.userID,
            subject:this.data.baidu_output.data.current_kw
          }).update({
            data:{
              time:new Date().toJSON().substring(0, 10),
              review_status:state
            }
          }).then(res=>{
            console.log("更新review",res)
            wx.showToast({
              title: '更新成功',
              icon: 'success',
              duration: 2000
            })
          }).catch(err=>{
            console.log("更新失败",err)
          })
        }
      }
      if (res.data.length==0) {
        DB.add({
          data:{
            // openid:this.data.userID,
            subject: feedback.current_kw,
            time: timestamp,
            review_background: feedback.definition,
            review_status: state
          }
        }).then(res=>{
          console.log("添加成功",res)
          wx.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 2000
          })
        }).catch(err=>{
          console.log("添加失败",err)
          wx.showToast({
            title: '保存失败',
            icon: 'error',
            duration: 2000
          })
        })
      }
    }).catch(err=>{
      console.log("云函数checkreview失败",err)
    })
  }
})